# -*- coding:utf-8 -*-
"""
@Time:2024/6/28
@Auth:Liu Zunzeng
@File:rectpack_python.py
"""
from src.container import CContainer
from rectpack import newPacker

class CAlgorithm2DBPP:
	def __init__(self, c: CContainer, stacks_tmp: list, smt: int):
		self.container = c
		self.stacks = stacks_tmp
		self.layout = []
		self.smt = smt

	def solve_by_rectpack(self):
		rectangles = []
		for i, s in enumerate(self.stacks):
			rectangles.append((s.lx, s.ly))
		bins = [(self.container.type.l_c , self.container.type.w_c), (self.container.type.l_c , self.container.type.w_c)]
		#bins = [(self.container.type.l_c - 0.4, self.container.type.w_c)]
		print("集装箱：", bins)

		packer = newPacker()

		# Add the rectangles to packing queue
		for idx, r in enumerate(rectangles):
			packer.add_rect(*r, idx)

		# Add the bins where the rectangles will be placed
		for idx, b in enumerate(bins):
			packer.add_bin(*b, idx)

		# Start packing
		print("--------------------------------------开始求解----------------------------------------")
		packer.pack()

		# Obtain number of bins used for packing
		nbins = len(packer)
		print("使用的集装箱数量：", nbins)

		# Index first bin
		abin = packer[0]
		print("集装箱里面的货物数量：", len(abin))

		# Bin dimmensions (bins can be reordered during packing)
		width, height = abin.width, abin.height

		# Number of rectangles packed into first bin
		nrect = len(packer[0])

		# First bin first rectangle
		rect = packer[0][0]
		print()

		# rect is a Rectangle object
		x = rect.x  # rectangle bottom-left x coordinate
		y = rect.y  # rectangle bottom-left y coordinate
		w = rect.width
		h = rect.height

		chosn_boxes = []
		boxes_dic = {}
		boxes_info = {}
		rotate_dic = {}
		for index1 , pack in enumerate(packer):
			area = 0
			for index, rect in enumerate(pack):
				print(f"{index1}集装箱的第{index}个货物的长和宽", (rect.width, rect.height), "id", rect.rid)
				boxes_info[rect.rid] = (rect.width, rect.height)
				if boxes_info[rect.rid] == rectangles[rect.rid]:
					rotate_dic[rect.rid] = 1
				else:
					rotate_dic[rect.rid] = 0
				boxes_dic[rect.rid] = (rect.x, rect.y)
				area += rect.width * rect.height
				chosn_boxes.append(rect)
			print("装载率：", area/(self.container.type.w_c * self.container.type.l_c))

		chosn_ids = []
		for rect in chosn_boxes:
			chosn_ids.append(rect.rid)

		p_value, x_value, y_value, r_value = [], [], [], []
		volume = 0

		for idx, stack in enumerate(self.stacks):
			'''print(boxes_info[idx], rectangles[idx],"的坐标是", round(boxes_dic[idx][0], 3), round(boxes_dic[idx][1], 3))
			if boxes_info[idx] == rectangles[idx]:
				rotate = 1
			else:
				rotate = 0'''
			if idx in chosn_ids:
				p_value.append(1)
				x_value.append(round(boxes_dic[idx][1], 3))
				y_value.append(round(boxes_dic[idx][0], 3))
				r_value.append(rotate_dic[idx])
				volume += stack.value
			else:
				p_value.append(0)
				x_value.append(0)
				y_value.append(0)
				r_value.append(0)

		return p_value, x_value, y_value, r_value, volume

